home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 5442 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  54.7 KB

  1. Path: news.wyoming.com!usenet
  2. From: dcromley@wyoming.com (RePost)
  3. Newsgroups: comp.lang.c++
  4. Subject: C++ FAQ:  re-posting #1/4
  5. Date: 5 Feb 1996 00:02:56 GMT
  6. Organization: wyoming.com LLC
  7. Message-ID: <4f3hfg$a96@horn.wyoming.com>
  8. NNTP-Posting-Host: cys-cap-6.wyoming.com
  9. Mime-Version: 1.0
  10. X-Newsreader: WinVN 0.99.2
  11.  
  12. (reposted from M. Cline to get them together)
  13. Summary: Please read this before posting to comp.lang.c++
  14.  
  15. comp.lang.c++ Frequently Asked Questions list (with answers, fortunately).
  16. Copyright (C) 1991-96 Marshall P. Cline, Ph.D.
  17. Posting 1 of 4.
  18.  
  19. UPDATED 1/96:
  20.  * Anonymous ftp fron.soe.clarkson.edu still does not work.
  21.  * No significant changes were made this month.
  22.  
  23. UPDATED 9/95:
  24.  * Added FAQ 41 on using a variable for the first dimension of a
  25.    multi-dimensional array
  26.  * Added FAQ 123 on the code from "Numerical Recipes"
  27.  * Added section 20 ("Libraries").  It's still pretty sparse, but it's a start
  28.  * Fixed a bug in FAQ 30 (there was no variable "i")
  29.  * Added FAQ 124 on dynamic linking to avoid bloated executables
  30.  * Added FAQ 32 on trying to "reopen" cin and cout in binary mode
  31.  * Added the access info to get the ANSI/ISO Committee Draft via ftp (FAQ 7)
  32.  
  33. UPDATED 7/95:
  34.  * Minor stuff (but not change in FTP access, below).
  35.  
  36. UPDATED 6/95:
  37.  * Corrected the mailing address where the ANSI-C++ Draft can be ordered
  38.  * Added a FAQ on floating point [Thanks to Phil Staite]
  39.  * Added a FAQ on multidimensional arrays [Thanks to Doug Shapter]
  40.  * Added a FAQ on interrupt service routines and ptrs to member functions
  41.  * Reorganized the FAQ on allocating all objects of a certain class via 'new'
  42.  
  43. UPDATED 5/95:
  44.  * Minor cosmetic changes
  45.  
  46. UPDATED 4/95:
  47.  * Added a question on a common BC++ Windows issue
  48.  * Fixed the ftp address for NIHCL
  49.  * Added an explanation that "ARM" is short for "Annotated Reference Manual"
  50.  
  51. UPDATED 3/95:
  52.  * Added a question on "delete this"
  53.  * Added two questions on iostreams and eof
  54.  * Fixed the entry on "c-mode" and "cc-mode" in Gnu emacs
  55.  
  56. UPDATED 1/95:
  57.  * A Chinese version of this document has been produced; details below.
  58.  
  59. UPDATED 12/94:
  60.  * Added a FAQ on STL (currently #115).
  61.  * Added a FAQ on name mangling (currently #119).
  62.  * Fixed typo in FAQ that compared composition with private inheritance.
  63.  * Corrected some spelling errors.
  64.  
  65. UPDATED 11/94:
  66.  * Added differentiator between "FAQ book" and "FAQ posting"
  67.  * Other cosmetic changes
  68.  
  69. UPDATED 10/94:
  70.  * Fixed a few typos
  71.  
  72. UPDATED 9/94:
  73.  * Minor cosmetic changes
  74.  
  75. UPDATED 8/94:
  76.  * Made it up-to-date with respect to "typeid" and "dynamic_cast".
  77.  * Made it up-to-date with respect to "mutable" and "const_cast".
  78.  * Rewrote most of the answers to provide general cleanup.
  79.  * The quotation marks are now "..." rather than `...' or ``...''
  80.  * Sample code lines start with a tab; no other lines starts with a tab.
  81.  * Everything was edited; minor modifications everywhere.
  82.  
  83. ==============================================================================
  84. SECTION 1: Introduction and table of contents
  85. ==============================================================================
  86.  
  87.         DOCUMENT:       Frequently-Asked-Questions for comp.lang.c++
  88.         REVISION:       Jan 31, 1996
  89.  
  90.         POSTING!=BOOK:  This C++ FAQ posting is NOT the same as the "FAQ book".
  91.                         The "FAQ book" ("C++ FAQs", Addison-Wesley, 1995) is
  92.                         5x larger than this posting.  See below for more.
  93.  
  94.         AUTHOR:         Marshall P. Cline, Ph.D.
  95.                         Paradigm Shift, Inc.
  96.                         One Park St. / Norwood, NY  13668
  97.                         voice: 315-353-6100
  98.                         fax:   315-353-6110
  99.                         email: cline@parashift.com
  100.  
  101.         COPYRIGHT:      Copyright (C), 1991-94 Marshall P. Cline, Ph.D.
  102.                         Permission to copy all or part of this work is granted,
  103.                         provided that the copies are not made or distributed
  104.                         for resale (except a nominal copy fee may be charged),
  105.                         and provided that the AUTHOR, COPYRIGHT, & NO WARRANTY
  106.                         sections are retained verbatim and are displayed
  107.                         conspicuously.  If anyone needs other permissions that
  108.                         aren't covered by the above, please contact the author.
  109.  
  110.         NO WARRANTY:    THIS WORK IS PROVIDED ON AN "AS IS" BASIS.  THE AUTHOR
  111.                         PROVIDES NO WARRANTY WHATSOEVER, EITHER EXPRESS OR
  112.                         IMPLIED, REGARDING THE WORK, INCLUDING WARRANTIES WITH
  113.                         RESPECT TO ITS MERCHANTABILITY OR FITNESS FOR ANY
  114.                         PARTICULAR PURPOSE.
  115.  
  116.         AVAILABILITY:   The old FTP site is no longer available.
  117.                         I am searching for an alternate FTP site.
  118.                         Watch this space for an FTP site next month.
  119.                         Please DON'T send suggestions for ftp sites
  120.                                 (my mailbox to overfloweth :-).
  121.  
  122.         SEE ALSO:       comp.lang.c FAQ appears every month in that newsgroup,
  123.                         and is maintained by Steve Summit (scs@eskimo.com).
  124.  
  125.         CHINESE TRANSLATION: A Chinese translation, encoded in "Big5" code
  126.                         (a 16-bit Chinese code used mostly in Taiwan)
  127.                         is now available for anonymous ftp at:
  128.              ftp://ftp.cis.nctu.edu.tw/Documents/News/comp.lang.c++/c-cppfaq.*
  129.  
  130. ==============================================================================
  131. SUBSECTION 1A: "FAQ book" versus "FAQ posting"
  132. ==============================================================================
  133.  
  134. Now that Addison-Wesley has published "C++ FAQs" by Cline and Lomow (1995,
  135. ISBN 0-201-58958-3), many people have asked about the relationship between the
  136. book and this posting.  Some who haven't seen the book have wondered whether
  137. the posting was equivalent to the book.  This section answers these questions.
  138.  
  139. The "FAQ book" (at bookstores starting Oct. 94) is loosely based on the same
  140. concepts as this posting.  However the FAQ book is approx five (5) times
  141. bigger than this posting, including thousands of cross references, external
  142. references, and index terms, as well as many programming examples.
  143.  
  144. ==============================================================================
  145. SUBSECTION 1B: Table of Contents
  146. ==============================================================================
  147.  
  148. ========== POSTING #1 ==========
  149.  
  150. SECTION 1: Introduction and table of contents
  151. SUBSECTION 1A: "FAQ book" versus "FAQ posting"
  152. SUBSECTION 1B: Table of Contents
  153. SUBSECTION 1C: Nomenclature and Common Abbreviations
  154.  
  155. SECTION 2: How should I post something? (READ BEFORE POSTING)
  156. Q1: Which newsgroup should I post my questions?
  157. Q2: How do I post a question about code that doesn't work correctly?
  158.  
  159. SECTION 3: Environmental/managerial issues
  160. Q3: What is OOP?  What is C++?
  161. Q4: What are some advantages of C++?
  162. Q5: Who uses C++?
  163. Q6: Are there any C++ standardization efforts underway?
  164. Q7: Where can I get a copy of the latest ANSI-C++ draft standard?
  165. Q8: Is C++ backward compatible with ANSI-C?
  166. Q9: How long does it take to learn C++?
  167.  
  168. SECTION 4: Basics of the paradigm
  169. Q10: What is a class?
  170. Q11: What is an object?
  171. Q12: What is a reference?
  172. Q13: What happens if you assign to a reference?
  173. Q14: How can you reseat a reference to make it refer to a different object?
  174. Q15: When should I use references, and when should I use pointers?
  175. Q16: What's the deal with inline functions?
  176.  
  177. SECTION 5: Constructors and destructors
  178. Q17: What's the deal with constructors?
  179. Q18: How can I make a constructor call another constructor as a primitive?
  180. Q19: What's the deal with destructors?
  181.  
  182. SECTION 6: Operator overloading
  183. Q20: What's the deal with operator overloading?
  184. Q21: What operators can/cannot be overloaded?
  185. Q22: Can I create a "**" operator for "to-the-power-of" operations?
  186.  
  187. SECTION 7: Friends
  188. Q23: What is a "friend"?
  189. Q24: Do "friends" violate encapsulation?
  190. Q25: What are some advantages/disadvantages of using friend functions?
  191. Q26: What does it mean that "friendship is neither inherited nor transitive"?
  192. Q27: Should my class declare a member function or a friend function?
  193.  
  194. SECTION 8: Input/output via <iostream.h> and <stdio.h>
  195. Q28: How can I provide printing for a "class Fred"?
  196. Q29: Why should I use <iostream.h> instead of the traditional <stdio.h>?
  197. Q30: Why does my input seem to process past the end of file?
  198. Q31: Why is my program ignoring my input request after the first iteration?
  199. Q32: How can I "reopen" cin and cout in binary mode under DOS and/or OS/2?
  200.  
  201. ========== POSTING #2 ==========
  202.  
  203. SECTION 9: Freestore management
  204. Q33: Does "delete p" delete the pointer "p", or the pointed-to-data, "*p"?
  205. Q34: Can I "free()" pointers allocated with "new"?  Can I "delete" pointers
  206.    alloc'd with "malloc()"?
  207. Q35: Why should I use "new" instead of trustworthy old malloc()?
  208. Q36: Why doesn't C++ have a "realloc()" along with "new" and "delete"?
  209. Q37: How do I allocate / unallocate an array of things?
  210. Q38: What if I forget the "[]" when "delete"ing array allocated via "new
  211.    Fred[n]"?
  212. Q39: Is it legal (and moral) for a member function to say "delete this"?
  213. Q40: How do I allocate multidimensional arrays using new?
  214. Q41: Does C++ have arrays whose length can be specified at run-time?
  215. Q42: How can I ensure objects of my class are always created via "new" rather
  216.    than as locals or global/static objects?
  217.  
  218. SECTION 10: Debugging and error handling
  219. Q43: How can I handle a constructor that fails?
  220. Q44: How should I handle resources if my constructors may throw exceptions?
  221.  
  222. SECTION 11: Const correctness
  223. Q45: What is "const correctness"?
  224. Q46: Should I try to get things const correct "sooner" or "later"?
  225. Q47: What is a "const member function"?
  226. Q48: What do I do if I want to update an "invisible" data member inside a
  227.    "const" member function?
  228. Q49: Does "const_cast" mean lost optimization opportunities?
  229.  
  230. SECTION 12: Inheritance
  231. Q50: Is inheritance important to C++?
  232. Q51: When would I use inheritance?
  233. Q52: How do you express inheritance in C++?
  234. Q53: Is it ok to convert a pointer from a derived class to its base class?
  235. Q54: Derived* --> Base* works ok; why doesn't Derived** --> Base** work?
  236. Q55: Does array-of-Derived is-NOT-a-kind-of array-of-Base mean arrays are
  237.    bad?
  238. SUBSECTION 12A: Inheritance -- Virtual functions
  239. Q56: What is a "virtual member function"?
  240. Q57: How can C++ achieve dynamic binding yet also static typing?
  241. Q58: Should a derived class replace ("override") a non-virtual fn from a base
  242.    class?
  243. Q59: What's the meaning of, "Warning: Derived::f(int) hides Base::f(float)"?
  244. SUBSECTION 12B: Inheritance -- Conformance
  245. Q60: Should I hide public member fns inherited from my base class?
  246. Q61: Is a "Circle" a kind-of an "Ellipse"?
  247. Q62: Are there other options to the "Circle is/isnot kind-of Ellipse"
  248.    dilemma?
  249. SUBSECTION 12C: Inheritance -- Access rules
  250. Q63: Why can't my derived class access "private" things from my base class?
  251. Q64: What's the difference between "public:", "private:", and "protected:"?
  252. Q65: How can I protect subclasses from breaking when I change internal parts?
  253. SUBSECTION 12D: Inheritance -- Constructors and destructors
  254. Q66: When my base class's constructor calls a virtual function, why doesn't my
  255.    derived class's override of that virtual function get invoked?
  256. Q67: Does a derived class destructor need to explicitly call the base
  257.    destructor?
  258. SUBSECTION 12E: Inheritance -- Private and protected inheritance
  259. Q68: How do you express "private inheritance"?
  260. Q69: How are "private inheritance" and "composition" similar?
  261. Q70: Which should I prefer: composition or private inheritance?
  262. Q71: Should I pointer-cast from a "privately" derived class to its base
  263.    class?
  264. Q72: How is protected inheritance related to private inheritance?
  265. Q73: What are the access rules with "private" and "protected" inheritance?
  266.  
  267. SECTION 13: Abstraction
  268. Q74: What's the big deal of separating interface from implementation?
  269. Q75: How do I separate interface from implementation in C++ (like Modula-2)?
  270. Q76: What is an ABC ("abstract base class")?
  271. Q77: What is a "pure virtual" member function?
  272. Q78: How can I provide printing for an entire hierarchy of classes?
  273. Q79: When should my destructor be virtual?
  274. Q80: What is a "virtual constructor"?
  275.  
  276. ========== POSTING #3 ==========
  277.  
  278. SECTION 14: Style guidelines
  279. Q81: What are some good C++ coding standards?
  280. Q82: Are coding standards necessary?  Are they sufficient?
  281. Q83: Should our organization determine coding standards from our C
  282.    experience?
  283. Q84: Should I declare locals in the middle of a fn or at the top?
  284. Q85: What source-file-name convention is best? "foo.C"? "foo.cc"? "foo.cpp"?
  285. Q86: What header-file-name convention is best? "foo.H"? "foo.hh"? "foo.hpp"?
  286. Q87: Are there any lint-like guidelines for C++?
  287.  
  288. SECTION 15: Keys for Smalltalk programmers to learn C++
  289. Q88: Why does C++'s FAQ have a section on Smalltalk? Is this
  290.    Smalltalk-bashing?
  291. Q89: What's the difference between C++ and Smalltalk?
  292. Q90: What is "static typing", and how is it similar/dissimilar to Smalltalk?
  293. Q91: Which is a better fit for C++: "static typing" or "dynamic typing"?
  294. Q92: How can you tell if you have a dynamically typed C++ class library?
  295. Q93: How do you use inheritance in C++, and is that different from Smalltalk?
  296. Q94: What are the practical consequences of diffs in Smalltalk/C++
  297.    inheritance?
  298. Q95: Do you need to learn a "pure" OOPL before you learn C++?
  299. Q96: What is the NIHCL?  Where can I get it?
  300.  
  301. SECTION 16: Reference and value semantics
  302. Q97: What is value and/or reference semantics, and which is best in C++?
  303. Q98: What is "virtual data," and how-can / why-would I use it in C++?
  304. Q99: What's the difference between virtual data and dynamic data?
  305. Q100: Should I normally use pointers to freestore allocated objects for my
  306.    data members, or should I use "composition"?
  307. Q101: What are relative costs of the 3 performance hits associated with
  308.    allocating member objects from the freestore?
  309. Q102: Are "inline virtual" member fns ever actually "inlined"?
  310. Q103: Sounds like I should never use reference semantics, right?
  311. Q104: Does the poor performance of ref semantics mean I should pass-by-value?
  312.  
  313. ========== POSTING #4 ==========
  314.  
  315. SECTION 17: Linkage-to/relationship-with C
  316. Q105: How can I call a C function "f(int,char,float)" from C++ code?
  317. Q106: How can I create a C++ function "f(int,char,float)" that is callable by
  318.    my C code?
  319. Q107: Why's the linker giving errors for C/C++ fns being called from C++/C
  320.    fns?
  321. Q108: How can I pass an object of a C++ class to/from a C function?
  322. Q109: Can my C function access data in an object of a C++ class?
  323. Q110: Why do I feel like I'm "further from the machine" in C++ as opposed to
  324.    C?
  325.  
  326. SECTION 18: Pointers to member functions
  327. Q111: Is the type of "ptr-to-member-fn" different from "ptr-to-fn"?
  328. Q112: How do I pass a ptr to member fn to a signal handler, X event callback,
  329.    etc?
  330. Q113: Why do I keep getting compile errors (type mismatch) when I try to use a
  331.    member function as an interrupt service routine?
  332. Q114: Why am I having trouble taking the address of a C++ function?
  333. Q115: How do I declare an array of pointers to member functions?
  334.  
  335. SECTION 19: Container classes and templates
  336. Q116: How can I insert/access/change elements from a linked
  337.    list/hashtable/etc?
  338. Q117: What's the idea behind "templates"?
  339. Q118: What's the syntax / semantics for a "function template"?
  340. Q119: What's the syntax / semantics for a "class template"?
  341. Q120: What is a "parameterized type"?
  342. Q121: What is "genericity"?
  343.  
  344. SECTION 20: Libraries
  345. Q122: Where can I get a copy of "STL"?
  346. Q123: Where can I ftp the code that accompanies "Numerical Recipes"?
  347. Q124: Why is my executable so large?
  348.  
  349. SECTION 21: Nuances of particular implementations
  350. Q125: GNU C++ (g++) produces big executables for tiny programs; Why?
  351. Q126: Is there a yacc-able C++ grammar?
  352. Q127: What is C++ 1.2?  2.0?  2.1?  3.0?
  353. Q128: If name mangling was standardized, could I link code compiled with
  354.    compilers from different compiler vendors?
  355.  
  356. SECTION 22: Miscellaneous technical and environmental issues
  357. SUBSECTION 22A: Miscellaneous technical issues:
  358. Q129: Why are classes with static data members getting linker errors?
  359. Q130: What's the difference between the keywords struct and class?
  360. Q131: Why can't I overload a function by its return type?
  361. Q132: What is "persistence"?  What is a "persistent object"?
  362. Q133: Why is floating point so inaccurate?  Why doesn't this print 0.43?
  363. SUBSECTION 22B: Miscellaneous environmental issues:
  364. Q134: Is there a TeX or LaTeX macro that fixes the spacing on "C++"?
  365. Q135: Where can I access C++2LaTeX, a LaTeX pretty printer for C++ source?
  366. Q136: Where can I access "tgrind," a pretty printer for C++/C/etc source?
  367. Q137: Is there a C++-mode for GNU emacs?  If so, where can I get it?
  368. Q138: Where can I get OS-specific FAQs answered (e.g.,BC++,DOS,Windows,etc)?
  369. Q139: Why does my DOS C++ program says "Sorry: floating point code not
  370.    linked"?
  371. Q140: Why does my BC++ Windows app crash when I'm not running the BC45 IDE?
  372. ==============================================================================
  373. SUBSECTION 1C: Nomenclature and Common Abbreviations
  374. ==============================================================================
  375.  
  376. Here are a few of the abbreviations/etc used in this article:
  377.  
  378.     term        meaning
  379.     ====        ===========
  380.     fn          function
  381.     fns         functions
  382.     param       parameter
  383.     ptr         pointer, a C/C++ construct declared by:  int * p;
  384.     ref         reference, a C++ construct declared by:  int & r;
  385.     OO          object-oriented
  386.     OOP         object-oriented programming
  387.     OOPL        object-oriented programming language
  388.     method      an alternate term for "member function"
  389.  
  390. ==============================================================================
  391. SECTION 2: How should I post something? (READ BEFORE POSTING)
  392. ==============================================================================
  393.  
  394. Q1: Which newsgroup should I post my questions?
  395.  
  396. Comp.lang.c++ is the best place to discuss the C++ language itself (e.g.,
  397. C++ code design, syntax, style).  Other newsgroups exist for discussion of
  398. topics which are specific to a particular system (e.g., MS Windows or UNIX)
  399. or topics which are not directly related to the C++ language (e.g., how to
  400. use your compiler).  Here's a list of some very active newsgroups and
  401. excerpts from their Frequently Asked Questions lists.  These excerpts
  402. should give you an idea of the type of topics frequently discussed there.
  403.  
  404.   comp.os.ms-windows.programmer.tools
  405.      This group is intended for discussions about the selection and use of
  406.      tools for Windows software development.
  407.   comp.os.ms-windows.programmer.misc
  408.      This group is for all other discussions about Windows software
  409.      development.
  410.   [There's one FAQ list for all the comp.os.ms-windows.programmer.* groups]
  411.      FAQ 5.7.1.  Accessing C++ classes in a DLL
  412.      FAQ 6.1.1.  A dialog as an MDI child window [with OWL]
  413.      FAQ 6.2.1.  Disabled menu choices become enabled [with MFC]
  414.      FAQ 8.1.5.  Using STRICT with windows.h
  415.      FAQ 10.  A programmer's bibliography
  416.  
  417.   comp.os.msdos.programmer
  418.      Much of the traffic is about language products (chiefly from Borland
  419.      and Microsoft).
  420.      FAQ 301. How can I read a character without [waiting for] the Enter key?
  421.      FAQ 412. How can I read, create, change, or delete the volume label?
  422.      FAQ 504. How do I configure a COM port and use it to transmit data?
  423.      FAQ 602. How can a C program send control codes to my printer?
  424.      FAQ 606. How can I find the Microsoft mouse position and button status?
  425.      FAQ 707. How can I write a TSR (terminate-stay-resident) utility?
  426.      FAQ B0. How can I contact [Borland, Microsoft]?
  427.      [note: this FAQ is not available at rtfm.mit.edu; it is at Simtel
  428.             (e.g., oak.oakland.edu) in /pub/msdos/info/faqp*.zip and Garbo
  429.             (garbo.uwasa.fi) in /pc/doc-net/faqp*.zip]
  430.   comp.os.msdos.programmer.turbovision [Borland's character-mode framework]
  431.  
  432.   comp.unix.programmer
  433.      FAQ 4.5)  How do I use popen() to open a process for reading AND writing?
  434.      FAQ 4.6)  How do I sleep() in a C program for less than one second?
  435.  
  436.   comp.unix.solaris (covers SunOS 4.x and Solaris)
  437.      FAQ 4)  Signal Primer
  438.      FAQ 5)  Waiting for Children to Exit
  439.  
  440.   gnu.g++.help
  441.      FAQ: Where can I find a demangler?
  442.      FAQ: Getting gcc/g++ binaries for Solaris 2.x
  443.      FAQ: What documentation exists for g++ 2.x?
  444.   gnu.g++.bug [bug reports for g++ -- see the g++ docs]
  445.  
  446.   comp.lang.c
  447.      FAQ 1.10: I'm confused.  NULL is guaranteed to be 0, but the null
  448.                pointer is not?
  449.      FAQ 2.3:  So what is meant by the "equivalence of pointers and
  450.                arrays" in C?
  451.      FAQ 4.2:  [Why doesn't "printf("%d\n," i++ * i++);" work?]
  452.      FAQ 7.1:  How can I write a function that takes a variable number
  453.                of arguments? [stdarg.h or varargs.h]
  454.      FAQ 10.4: How do I declare an array of pointers to functions returning
  455.                pointers to functions returning pointers to characters?
  456.  
  457. Also check out the newsgroups comp.graphics, comp.sources.wanted,
  458. comp.programming, and comp.object (its FAQ is an excellent introduction and
  459. overview of OOP terms and concepts).  Remember that comp.std.c++ is for
  460. discussion DIRECTLY related to the evolving ANSI/ISO C++ Standard (see more
  461. below).
  462.  
  463. There's rarely a need to crosspost a question to one of the above
  464. newsgroups and comp.lang.c++ (readers in the system-specific newsgroups
  465. aren't programming in machine language, ya know).  It's bad netiquette to
  466. crosspost widely because your problem is "really important."  If you don't
  467. get an answer in the "right" newsgroup and feel you must post here, at
  468. least consider redirecting followups back to the appropriate newsgroup.
  469.  
  470. Before posting a question to any newsgroup you should read it's FAQ list.
  471. An answer to your question is likely to be there, saving you the time of
  472. posting and saving thousands of other people around the world the time of
  473. reading your question.  People answering a FAQ are likely to be annoyed for
  474. having to answer it for the umpteenth time, or they're likely to be giving
  475. you a wrong or incomplete answer since they haven't read the FAQ either.
  476.  
  477. Frequently Asked Questions lists are available 24-hours a day via anonymous
  478. ftp (rtfm.mit.edu in /pub/usenet/comp.what.ever) or e-mail server (send a
  479. message with the line "help" to mail-server@rtfm.mit.edu).  See the article
  480. "Introduction to the *.answers newsgroups" in the newsgroup news.answers or
  481. news.announce.newusers (which contains many other must-read articles) for
  482. more information.
  483.  
  484. ==============================================================================
  485.  
  486. Q2: How do I post a question about code that doesn't work correctly?
  487.  
  488. Here's some guidelines you should follow that will help people reading
  489. comp.lang.c++ help you with an answer to your programming problem.
  490.  
  491. 1. Please read the previous FAQ to make sure that your question is about the
  492.    C++ language and not a question about programming on your system (e.g.,
  493.    graphics, printers, devices, etc.) or using your compilation
  494.    environment (e.g., "the IDE crashes when I...," "how do you turn off
  495.    warnings about...," "how do I tell it to link my libraries").  If you
  496.    want to know why your virtual CmOk() function isn't being called in
  497.    your OWL program, your question is probably more appropriate in the
  498.    Windows programming newsgroup.  If you can write a small stand-alone
  499.    program which exhibits the same undesired compiler error or behavior
  500.    as your OWL program, by all means post here in comp.lang.c++ since C++
  501.    programmers using other systems could be of help.
  502.  
  503. 2. Be descriptive in the subject line.  "C++ problem" leaves a lot to the
  504.    imagination.  "Problem new'ing a multi-dimensional array" is good.
  505.    Refrain from exclamation points, cries for HELPPP, and the once funny
  506.    "SEX SEX SEX."  If you think the problem is specific to your compiler,
  507.    you might want to mention the compiler/version in the subject line.
  508.  
  509. 3. Post code that is complete and compilable.  It's extremely difficult
  510.    to debug or reconstruct a program from a human language description.
  511.    By "complete code" I mean that any types and functions used are
  512.    declared, headers are #include'd, etc.  Please strip the code down to
  513.    the bare essentials.  We don't need a program that does something
  514.    useful at run-time, or even links.  We just need to be able to
  515.    reproduce the undesired compiler error (possibly on a different
  516.    compiler).  By "compilable code" I mean that it doesn't contain a
  517.    bunch of uncommented ellipses or line numbers at the beginning of each
  518.    line:
  519.  
  520.         14:     #include <iostream.h>
  521.         15:     class Foo { ... };  // this is annoying
  522.  
  523.    Try to organize the code into one linear program instead of making us cut
  524.    out and create header files.  Be very careful if you are typing the code
  525.    into your article -- it's often difficult to tell whether something is a
  526.    typo or the real cause of the problem.  Try using your editor's
  527.    cut&paste or "insert file" feature instead.
  528.  
  529. 4. Mention what compiler, compiler version, and system you're using.  I
  530.    know, I just said that system-specific questions should go to a
  531.    system-specific newsgroup, but compiler information is often very
  532.    useful in diagnosing the problem: ("yeah, I remember Acme 1.2 having
  533.    lots of problems in this area").  It also warns other users of that
  534.    compiler about possible bugs.
  535.  
  536. 5. Show us the exact compiler and linker options and libraries you used
  537.    when building your program.
  538.  
  539. 6. List the exact error message and where the error was given.  "Virtual
  540.    functions don't work" doesn't tell us whether its a compile-, link-, or
  541.    run-time problem.  If the problem is at run-time, give a good
  542.    description of the behavior and any relevant information about your
  543.    system setup.
  544.  
  545. 7. Include a working e-mail address in your signature.  If the address in
  546.    given your article's "From:" line is not correct, please notify your
  547.    system administrator.  Until it is fixed, add a "Reply-To:" line to
  548.    your headers that uses your correct e-mail address.
  549.  
  550. 8. Please read the rest of this FAQ -- chances are your problem, or a
  551.    closely related problem, is discussed here.  Thank you and I hope these
  552.    suggestions help you find a solution to your problem.
  553.  
  554. ==============================================================================
  555. SECTION 3: Environmental/managerial issues
  556. ==============================================================================
  557.  
  558. Q3: What is OOP?  What is C++?
  559.  
  560. OO programming techniques are the best way we know of to develop large, complex
  561. software applications and systems.
  562.  
  563. C++ is an OO programming language.  C++ can be used both as an OOPL and simply
  564. "as a better C."  However if you use it "as a better C," don't expect to get
  565. the benefits of object-oriented programming.
  566.  
  567. OO hype: the software industry is "failing" to meet demands for large, complex
  568. software systems.  But this "failure" is actually due to our SUCCESSES: our
  569. successes have propelled users to ask for more.  Unfortunately we created a
  570. market hunger that the "structured" analysis, design and programming techniques
  571. couldn't satisfy.  This required us to create a better paradigm.
  572.  
  573. ==============================================================================
  574.  
  575. Q4: What are some advantages of C++?
  576.  
  577. GROWTH OF C++: C++ is by far the most popular OOPL.  The number of C++ users is
  578. doubling every 7.5 to 9 months.  Knowing C++ is a good resume-stuffer (but use
  579. it as an OOPL rather than just as a better C).
  580.  
  581. ENCAPSULATION: Hiding our data structures allows us to change one chunk of a
  582. system without breaking other chunks.  We provide our software chunks (we call
  583. them "classes") with safe interfaces.  Users of a chunk use its interface only.
  584. The relatively volatile "implementation" of this interface is "encapsulated"
  585. ("put into a capsule") to prevent users from becoming reliant on its temporary
  586. decisions.  In simple C, this was done by making a module's data "static", thus
  587. preventing another module from accessing our module's bits.
  588.  
  589. MULTIPLE INSTANCES: The typical C solution to encapsulation (see above) doesn't
  590. support multiple instances of the data (it's hard to make multiple instances of
  591. a module's "static" data).  If we needed multiple instances in C, we used a
  592. "struct" (but this doesn't support "encapsulation").  In C++, we can have both
  593. multiple instances and encapsulation via a "class": the "public" part of a
  594. class contains the class's interface (normally these are a special kind of
  595. function called a "member function"), and the "private" part of a class
  596. contains the class's implementation (typically these are where the bits live).
  597.  
  598. INLINE FUNCTION CALLS: In straight C, you can achieve "encapsulated structs" by
  599. putting a "void*" in a struct (the access functions use pointer casts).  This
  600. forfeits type safety, and also imposes a function call to access even trivial
  601. fields of the struct (if you allowed direct access to the struct's fields, the
  602. underlying data structure would be difficult to change since too many chunks
  603. would RELY on it being the "old" way).  Function call overhead is small, but
  604. can add up.  C++ classes allow function calls to be expanded "inline," so you
  605. have: the 1) safety of encapsulation, 2) convenience of multiple instances, 3)
  606. speed of direct access.  Furthermore the parameter types of these inline
  607. functions are checked by the compiler, an improvement over C's #define macros.
  608.  
  609. OVERLOADING OPERATORS: C++ lets you overload the standard operators on a class,
  610. which lets users exploit their intuition (e.g., "myString + yourString" might
  611. do string concatenation, "myDate++" might increment the date, "z1 * z2" might
  612. multiply complex numbers z1 and z2, "a[i]" might access the "i"th element of
  613. the "linked list" called "a", etc.  You can even have "smart pointers" that
  614. could "point" to a disk record or wherever ("x = *p" could "dereference" such a
  615. pointer, which could seek to the location on disk where p "points" and return
  616. its value").  This allows users to program in the language of the problem
  617. domain rather than in the language of the machine.
  618.  
  619. INHERITANCE: We still have just scratched the surface.  In fact, we haven't
  620. even gotten to the "object-oriented" part yet!  Suppose you have a Stack data
  621. type with operations push, pop, etc.  Suppose you want an InvertableStack,
  622. which is "just like" Stack except it also has an "invert" operation.  In "C"
  623. style, you'd have to either (1) modify the existing Stack module (trouble if
  624. "Stack" is being used by others), or (2) copy Stack into another file and text
  625. edit that file (results in lots of code duplication, another chance to break
  626. something tricky in the Stack part of InvertableStack, and especially twice as
  627. much code to maintain).  C++ provides a much cleaner solution: inheritance.
  628. You say "InvertableStack inherits everything from Stack, and InvertableStack
  629. adds the invert operation."  Done.  Stack itself remains "closed" (untouched,
  630. unmodified), and InvertableStack doesn't duplicate the code for push/pop/etc.
  631.  
  632. POLYMORPHISM AND DYNAMIC BINDING: The real power of OOP isn't just inheritance,
  633. but is the ability to pass an InvertableStack around as if it actually were a
  634. Stack.  This is "safe" since (in C++ at least) the is-a relation follows public
  635. inheritance (i.e., a InvertableStack is-a Stack that can also invert itself).
  636. Polymorphism and dynamic binding are easiest to understand from an example, so
  637. here's a "classic": a graphical draw package might deal with Circles, Squares,
  638. Rectangles, general Polygons, and Lines.  All of these are Shapes.  Most of the
  639. draw package's functions need a "Shape" parameter (as opposed to some
  640. particular kind of shape like Square).  E.g., if a Shape is picked by a mouse,
  641. the Shape might get dragged across the screen and placed into a new location.
  642. Polymorphism and dynamic binding allow the code to work correctly even if the
  643. compiler knows only that the parameter is a "Shape" without knowing the exact
  644. kind of Shape it is.  Furthermore suppose the "pick_and_drag(Shape*) function
  645. just mentioned was compiled on Tuesday, and on Wednesday you decide to add the
  646. Hexagon shape.  Strange as it sounds, pick_and_drag() will still work with
  647. Hexagons, even though the Hexagon didn't even exist when pick_and_drag() was
  648. compiled!!  (it's not really "amazing" once you understand how the C++ compiler
  649. does it -- but it's still very convenient!)
  650.  
  651. ==============================================================================
  652.  
  653. Q5: Who uses C++?
  654.  
  655. Lots and lots of companies and government sites.  Lots.
  656.  
  657. Statistically, 5 people became new C++ programmers while you read the words of
  658. the previous FAQ.
  659.  
  660. ==============================================================================
  661.  
  662. Q6: Are there any C++ standardization efforts underway?
  663.  
  664. Yes; ANSI (American) and ISO (International) groups are working closely with
  665. each other.  The ANSI-C++ committee is called "X3J16".  The ISO C++ standards
  666. group is called "WG21".  The major players in the ANSI/ISO C++ standards
  667. process includes just about everyone:
  668.  
  669. AT&T, IBM, DEC, HP, Sun, MS, Borland, Zortech, Apple, OSF, etc ad nauseum.
  670. About 70 people attend each meeting.  People come from USA, UK, Japan, Germany,
  671. Sweden, Denmark, France, ... (all have "local" committees sending official
  672. representatives and conducting "local" meetings).
  673.  
  674. ==============================================================================
  675.  
  676. Q7: Where can I get a copy of the latest ANSI-C++ draft standard?
  677.  
  678. The ISO Committee Draft for C++ and the ANSI C++ Draft (the document that is
  679. going out for public review) is available from:
  680.         http://www.cygnus.com/~mrs/wp-draft
  681.  
  682. You can also get Postscript and Adobe Acrobat versions from:
  683.         ftp://research.att.com/dist/stdc++/WP
  684.  
  685. You can get HTML and ASCII versions:
  686.         ftp://ftp.cygnus.com/pub/g++
  687.  
  688. You can also get a paper copy from:
  689.         X3 Secretariat
  690.         1250 Eye Street NW
  691.         Suite 200
  692.         Washington, DC  20005
  693.         202-626-5738
  694.  
  695. You can also order via email:
  696.         lbarra@itic.nw.dc.us (Lynn Barra)
  697.  
  698. Ask for the latest version of "Draft Proposed American National Standard for
  699. Information Systems -- Programming Language C++" which is document number
  700. CD14882.  It is typically shipped 2-day FedEx (within the continental US), so
  701. people usually get it quickly.
  702.  
  703. ==============================================================================
  704.  
  705. Q8: Is C++ backward compatible with ANSI-C?
  706.  
  707. Almost.
  708.  
  709. C++ is as close as possible to compatible with C, but no closer.  In practice,
  710. the major difference is that C++ requires prototypes, and that "f()" declares a
  711. function that takes no parameters (in C, "f()" is the same as "f(...)").  There
  712. are some very subtle differences as well, like sizeof('x') is equal to
  713. sizeof(char) in C++ but is equal to sizeof(int) in C.  Also, C++ puts structure
  714. "tags" in the same namespace as other names, whereas C requires an explicit
  715. "struct" (the "typedef struct Fred Fred" technique still works, but is
  716. redundant in C++).
  717.  
  718. ==============================================================================
  719.  
  720. Q9: How long does it take to learn C++?
  721.  
  722. Companies like Paradigm Shift, Inc. successfully teach standard industry "short
  723. courses", where we compress a university semester course into one 40hr work
  724. week.  However true mastery takes experience; there's no substitute for time.
  725. Hands-on projects are essential, since they allow concepts to "gel."
  726.  
  727. It takes 6-12 months to become proficient in C++/OOP.  Less if the developers
  728. have easy access to a "local" body of experts, more if there isn't a "good"
  729. general purpose C++ class library available.  To become one of these experts
  730. who can mentor others takes around 3 years.
  731.  
  732. Some people never make it.  You don't have a chance unless you are teachable
  733. and have personal drive.  As a bare minimum on "teachability," you have to be
  734. able to admit when you've are wrong.  As a bare minimum on "drive," you must
  735. be willing to put in some extra hours (changing the way you think [a paradigm
  736. shift] is a LOT more painful than learning a few new facts).
  737.  
  738. ==============================================================================
  739. SECTION 4: Basics of the paradigm
  740. ==============================================================================
  741.  
  742. Q10: What is a class?
  743.  
  744. The fundamental building block of OO software.
  745.  
  746. A class defines a data type, much like a struct would be in C.  In a computer
  747. science sense, a type consists of both a set of states AND a set of operations
  748. which transition between those states.  Thus "int" is a "type" because it has
  749. both a set of states AND it has operations like "add two ints" or "int*int,"
  750. etc.  In exactly the same way, a "class" provides a set of (usually public)
  751. operations, and a set of (usually non-public) data bits representing the
  752. abstract values that instances of the type can have.  From a C language
  753. perspective, a class is a struct whose members default to "private".
  754.  
  755. Think of "int" as a class that has methods called "operator++", etc.
  756.  
  757. ==============================================================================
  758.  
  759. Q11: What is an object?
  760.  
  761. A region of storage with associated semantics.
  762.  
  763. After the declaration "int i;" we say that "i is an object of type int."  In
  764. C++/OOP, "object" usually means "an instance of a class."  Thus a class defines
  765. the behavior of possibly many objects (instances).
  766.  
  767. ==============================================================================
  768.  
  769. Q12: What is a reference?
  770.  
  771. An alias (an alternate name) for an object.
  772.  
  773. References are frequently used for pass-by-reference:
  774.  
  775.         void swap(int& i, int& j)
  776.         {
  777.           int tmp = i;
  778.           i = j;
  779.           j = tmp;
  780.         }
  781.  
  782.         main()
  783.         {
  784.           int x, y;
  785.           //...
  786.           swap(x,y);
  787.         }
  788.  
  789. Here "i" and "j" are aliases for main's "x" and "y" respectively.  In other
  790. words, "i" IS "x" -- not a pointer to "x", nor a copy of "x", but "x" itself.
  791. Anything you do to "i" gets done to "x", and vise versa.
  792.  
  793. Underneath it all, references are typically implemented by pointers.  The
  794. effect is as if you used the C style pass-by-pointer, but the "&" is moved from
  795. the caller into the callee, and you eliminate all the "*"s.
  796.  
  797. ==============================================================================
  798.  
  799. Q13: What happens if you assign to a reference?
  800.  
  801. You change the referrent (the object to which the reference refers).
  802.  
  803. Remember: the reference IS the referrent, so changing the reference changes the
  804. referrent (a reference is an "Lvalue" [something that can appear on the
  805. "L"eft-hand-side of an assignment statement] for the referrent).
  806.  
  807. This insight can be pushed a bit farther by allowing references to be RETURNED.
  808. This allows function calls on the left hand side of an assignment statement,
  809. which is useful with operator overloading.
  810.  
  811. ==============================================================================
  812.  
  813. Q14: How can you reseat a reference to make it refer to a different object?
  814.  
  815. No way.
  816.  
  817. Unlike a pointer, once a reference is bound to an object, it can NOT be
  818. "reseated" to another object.  The reference itself isn't an object (it has no
  819. address; taking the address of a reference gives you the address of the
  820. referrent; remember: the reference IS its referrent).
  821.  
  822. You can't separate the reference from the referent.
  823.  
  824. ==============================================================================
  825.  
  826. Q15: When should I use references, and when should I use pointers?
  827.  
  828. Use references when you can, and pointers when you have to.
  829.  
  830. References are usually preferred over ptrs whenever you don't need "reseating"
  831. (see previous FAQ).  This usually means that references are most useful in a
  832. class's public interface.  References typically appear on the skin of an
  833. object, and pointers on the inside.
  834.  
  835. The exception to the above is where a function's parameter or return value
  836. needs a "sentinel" reference.  This is usually best done by returning/taking a
  837. pointer, and giving the NULL pointer this special significance (references
  838. should always alias objects, not a dereferenced NULL ptr).
  839.  
  840. NOTE: Old line C programmers sometimes don't like references since they provide
  841. reference semantics that isn't explicit in the caller's code.  After some C++
  842. experience, however, one quickly realizes this is a form of information hiding,
  843. which is an asset rather than a liability.  E.g., programmers should write code
  844. in the language of the problem rather than the language of the machine.
  845.  
  846. ==============================================================================
  847.  
  848. Q16: What's the deal with inline functions?
  849.  
  850. An inline function is a function whose code gets inserted into the caller's
  851. code stream.  Like a macro, inline functions improve performance by avoiding
  852. the overhead of the call itself and (especially!) by the compiler being able to
  853. optimize THROUGH the call ("procedural integration").  Unlike macros, inline
  854. functions avoid infamous macro errors by evaluating all arguments exactly once
  855. (the "call" is semantically like a regular function call, only faster).  Also
  856. unlike macros, argument types are checked, and necessary conversions are
  857. performed correctly (macros are bad for your health; don't use them unless you
  858. absolutely have to).
  859.  
  860. Beware that overuse of inline functions can cause code bloat, which can in
  861. turn have a negative performance impact in paging environments.
  862.  
  863. They are declared by using the "inline" keyword when the function is defined:
  864.  
  865.         inline void f(int i, char c) { /*...*/ }
  866.  
  867. or by including the function definition itself within a class:
  868.  
  869.         class Fred {
  870.         public:
  871.           void f(int i, char c) { /*...*/ }
  872.         };
  873.  
  874. or by defining the member function as "inline" outside the class:
  875.  
  876.         class Fred {
  877.         public:
  878.           void f(int i, char c);
  879.         };
  880.  
  881.         inline void Fred::f(int i, char c) { /*...*/ }
  882.  
  883. ==============================================================================
  884. SECTION 5: Constructors and destructors
  885. ==============================================================================
  886.  
  887. Q17: What's the deal with constructors?
  888.  
  889. Constructors build objects from dust.
  890.  
  891. Constructors are like "init functions"; they turn a pile of arbitrary bits into
  892. a living object.  Minimally they initialize internally used fields.  They may
  893. also allocate resources (memory, files, semaphores, sockets, etc).
  894.  
  895. "ctor" is a typical abbreviation for constructor.
  896.  
  897. ==============================================================================
  898.  
  899. Q18: How can I make a constructor call another constructor as a primitive?
  900.  
  901. No way.
  902.  
  903. Dragons be here: if you call another constructor, the compiler initializes a
  904. temporary local object; it does NOT initialize "this" object.  You can combine
  905. both constructors by using a default parameter, or you can share their common
  906. code in a private "init()" member function.
  907.  
  908. ==============================================================================
  909.  
  910. Q19: What's the deal with destructors?
  911.  
  912. A destructor gives an object its last rites.
  913.  
  914. Destructors are used to release any resources allocated by the object.  E.g., a
  915. Lock class might lock a semaphore, and the destructor will release that
  916. semaphore.  The most common example is when the constructor uses "new", and the
  917. destructor uses "delete".
  918.  
  919. Destructors are a "prepare to die" method.  They are often abbreviated "dtor".
  920.  
  921. ==============================================================================
  922. SECTION 6: Operator overloading
  923. ==============================================================================
  924.  
  925. Q20: What's the deal with operator overloading?
  926.  
  927. It allows users of your classes to use intuitive syntax.
  928.  
  929. Operator overloading allows C/C++ operators to have user-defined meanings on
  930. user-defined types (classes).  They're syntactic sugar for function calls:
  931.  
  932.         class Fred {
  933.         public:
  934.           //...
  935.         };
  936.  
  937.         #if 0
  938.           Fred add(Fred, Fred);         //without operator overloading
  939.           Fred mul(Fred, Fred);
  940.         #else
  941.           Fred operator+(Fred, Fred);   //with operator overloading
  942.           Fred operator*(Fred, Fred);
  943.         #endif
  944.  
  945.         Fred f(Fred a, Fred b, Fred c)
  946.         {
  947.           #if 0
  948.             return add(add(mul(a,b), mul(b,c)), mul(c,a));  //without...
  949.           #else
  950.             return a*b + b*c + c*a;                         //with...
  951.           #endif
  952.         }
  953.  
  954. ==============================================================================
  955.  
  956. Q21: What operators can/cannot be overloaded?
  957.  
  958. Most can be overloaded. The only C operators that can't be are "." and "?:"
  959. (and "sizeof," which is technically an operator).  C++ adds a few of its own
  960. operators, most of which can be overloaded except "::" and ".*".
  961.  
  962. Here's an example of the subscript operator (it returns a reference).  First
  963. withOUT operator overloading:
  964.  
  965.         class Array {
  966.         public:
  967.           #if 0
  968.             int& elem(unsigned i) { if (i>99) error(); return data[i]; }
  969.           #else
  970.             int& operator[] (unsigned i) { if (i>99) error(); return data[i]; }
  971.           #endif
  972.         private:
  973.           int data[100];
  974.         };
  975.  
  976.         main()
  977.         {
  978.           Array a;
  979.  
  980.           #if 0
  981.             a.elem(10) = 42;
  982.             a.elem(12) += a.elem(13);
  983.           #else
  984.             a[10] = 42;
  985.             a[12] += a[13];
  986.           #endif
  987.         }
  988.  
  989. ==============================================================================
  990.  
  991. Q22: Can I create a "**" operator for "to-the-power-of" operations?
  992.  
  993. Nope.
  994.  
  995. The names of, precedence of, associativity of, and arity of operators is fixed
  996. by the language.  There is no "**" operator in C++, so you cannot create one
  997. for a class type.
  998.  
  999. If you're in doubt, consider that "x ** y" is the same as "x * (*y)" (in other
  1000. words, the compiler assumes "y" is a pointer).  Besides, operator overloading
  1001. is just syntactic sugar for function calls.  Although this particular syntactic
  1002. sugar can be very sweet, it doesn't add anything fundamental.  I suggest you
  1003. overload "pow(base,exponent)" (a double precision version is in <math.h>).
  1004.  
  1005. BTW: operator^ can work, except it has the wrong precedence and associativity.
  1006.  
  1007. ==============================================================================
  1008. SECTION 7: Friends
  1009. ==============================================================================
  1010.  
  1011. Q23: What is a "friend"?
  1012.  
  1013. Something to allow your class to grant access to another class or function.
  1014.  
  1015. Friends can be either functions or other classes.  A class grants access
  1016. privileges to its friends.  Normally a developer has political and technical
  1017. control over both the friends and methods of a class (else you need permission
  1018. from the owner of the other pieces when you want to update your class).
  1019.  
  1020. ==============================================================================
  1021.  
  1022. Q24: Do "friends" violate encapsulation?
  1023.  
  1024. If they're used properly, they actually ENHANCE encapsulation.
  1025.  
  1026. You often need to split a class in half when the two halves will have different
  1027. numbers of instances or different lifetimes.  In these cases, the two halves
  1028. usually need direct access to each other (the two halves USED to be in the same
  1029. class, so you haven't INCREASED the number of methods that have direct access
  1030. to a data structure; you've simply MOVED some of those methods).  The safest
  1031. way to implement this is to make the two halves friends of each other.
  1032.  
  1033. If you use friends like just described, you'll keep private things private.  In
  1034. a naive effort to avoid using friendship in situations like the above, many
  1035. people actually destroy encapsulation by either using public data (grotesque!),
  1036. or by making the data accessible between the halves via public get/set methods.
  1037. Having a public get and set method for a private datum is ok only when the
  1038. private datum "makes sense" from outside the class (from a user's perspective).
  1039. In many cases, these get/set methods are almost as bad as public data: they
  1040. hide (only) the NAMES of the private data members, but they don't hide the
  1041. existence of the private data members.
  1042.  
  1043. Similarly, if you use friend functions as a syntactic variant of a class's
  1044. public access functions, they don't violate encapsulation any more than a
  1045. member function violates encapsulation.  In other words, a class's friends and
  1046. members ARE the encapsulation barrier, as defined by the class itself.
  1047.  
  1048. ==============================================================================
  1049.  
  1050. Q25: What are some advantages/disadvantages of using friend functions?
  1051.  
  1052. They provide a degree of freedom in the interface design options.
  1053.  
  1054. Member fns and friend fns are equally privileged (100% vested).  The major
  1055. difference is that a friend function is called like "f(x)", while a member is
  1056. called like "x.f()".  Thus friend fns allow the class's designer to select
  1057. the syntax that is deemed most readable, which lowers maintenance costs.
  1058.  
  1059. The major disadvantage of friend functions is that they require an extra line
  1060. of code when you want dynamic binding.  To get the effect of a virtual friend,
  1061. the friend function should call a hidden (usually "protected:") virtual member
  1062. fn; e.g., "void f(Base& b) { b.do_f(); }".  Derived classes override the hidden
  1063. virtual member function ("void Derived::do_f()"), NOT the friend function.
  1064.  
  1065. ==============================================================================
  1066.  
  1067. Q26: What does it mean that "friendship is neither inherited nor transitive"?
  1068.  
  1069. The privileges of friendship aren't inherited: derived classes of a friend
  1070. aren't necessarily friends (I may declare you as my friend, but that doesn't
  1071. mean I necessarily trust your kids).  If class "Base" declares "f()" to be a
  1072. friend, "f()" doesn't have any automatic special access rights to the extra
  1073. stuff declared in derived class, "Derived."
  1074.  
  1075. The privileges of friendship aren't transitive: friends of a friend class
  1076. aren't necessarily friends of the original class (a friend of a friend isn't
  1077. necessarily a friend).  E.g., if class "Fred" declares class "Wilma" as a
  1078. friend, and class "Wilma" declares "f()" as a friend, "f()" doesn't necessarily
  1079. have any special access rights to "Fred".
  1080.  
  1081. ==============================================================================
  1082.  
  1083. Q27: Should my class declare a member function or a friend function?
  1084.  
  1085. Use a member when you can, and a friend when you have to.
  1086.  
  1087. Sometimes friends are syntactically better (e.g., in class "Fred", friend fns
  1088. allow the "Fred" param to be second, while members require it to be first).
  1089. Another good use of friend functions are the binary infix arithmetic operators
  1090. (e.g., "aComplex + aComplex" probably should be defined as a friend rather than
  1091. a member, since you want to allow "aFloat + aComplex" as well; recall members
  1092. don't allow promotion of the left hand arg, since that would change the class
  1093. of the object that is the recipient of the member function invocation).
  1094.  
  1095. In other cases, choose a member function over a friend function.
  1096.  
  1097. ==============================================================================
  1098. SECTION 8: Input/output via <iostream.h> and <stdio.h>
  1099. ==============================================================================
  1100.  
  1101. Q28: How can I provide printing for a "class Fred"?
  1102.  
  1103. Provide a friend operator<<:
  1104.  
  1105.         class Fred {
  1106.         public:
  1107.           friend ostream& operator<< (ostream& o, const Fred& fred)
  1108.             { return o << fred.i; }
  1109.           //...
  1110.         private:
  1111.           int i;    //just for illustration
  1112.         };
  1113.  
  1114. We use a friend rather than a member since the "Fred" parameter is second
  1115. rather than first.  Input is similar, but the signature is:
  1116.  
  1117.         istream& operator>> (istream& i, Fred& fred);
  1118.                                       // ^^^^^------- not "const Fred& fred"!
  1119.  
  1120. ==============================================================================
  1121.  
  1122. Q29: Why should I use <iostream.h> instead of the traditional <stdio.h>?
  1123.  
  1124. Increase type safety, reduce errors, improve performance, allow extensibility,
  1125. and provide subclassability.
  1126.  
  1127. Printf is arguably not broken, and scanf is perhaps livable despite being error
  1128. prone, however both are limited with respect to what C++ I/O can do.  C++ I/O
  1129. (using "<<" and ">>") is, relative to C (using "printf()" and "scanf()"):
  1130.  
  1131.  * Type safe -- type of object being I/O'd is known statically by the compiler,
  1132.    rather than via dynamically tested via "%" fields.
  1133.  
  1134.  * Less error prone -- redundant info increases the chance of errors.  C++ I/O
  1135.    has no redundant "%" tokens to get right.
  1136.  
  1137.  * Faster -- printf is an "interpreter" of a tiny language whose constructs
  1138.    mainly include "%" fields; it uses these fields to select the right
  1139.    formatting primitive at run-time.  C++ I/O picks these routines statically
  1140.    based on actual types of the args.  This improves performance.
  1141.  
  1142.  * Extensible -- the C++ I/O mechanism allows new user-defined types to be
  1143.    added without breaking existing code (imagine the chaos if everyone was
  1144.    simultaneously adding new incompatible "%" fields to printf and scanf?!).
  1145.  
  1146.  * Subclassable -- ostream and istream (the C++ replacements for FILE*) are
  1147.    real classes, and hence subclassable.  This means you can have other user
  1148.    defined things that look and act like streams, yet that do whatever strange
  1149.    and wonderful things you want.  You automatically get to use the zillions of
  1150.    lines of I/O code written by users you don't even know, and they don't need
  1151.    to know about your "extended stream" class.
  1152.  
  1153. ==============================================================================
  1154.  
  1155. Q30: Why does my input seem to process past the end of file?
  1156. Because the eof state is not set until after a read is attempted past the
  1157. end of file.  That is, reading the last byte from a file does not set the
  1158. eof state.
  1159.  
  1160. If your code looks like this:
  1161.  
  1162.         int i = 0;
  1163.         while (! cin.eof())  {
  1164.           cin >> x;
  1165.           ++i;
  1166.           // work with x
  1167.         }
  1168.  
  1169. Then you have an off by one error with the count i.
  1170. What you really need is:
  1171.  
  1172.         int i;
  1173.         while (cin >> x)  {
  1174.           ++i;
  1175.           // work with x
  1176.         }
  1177.  
  1178. ==============================================================================
  1179.  
  1180. Q31: Why is my program ignoring my input request after the first iteration?
  1181. Because the numerical extractor leaves non digits behind in the input buffer.
  1182.  
  1183. If your code looks like this:
  1184.  
  1185.         char name[1000];
  1186.         int age;
  1187.  
  1188.         for (;;) {
  1189.           cout << "Name: ";
  1190.           cin >> name;
  1191.           cout << "Age: ";
  1192.           cin >> age;
  1193.         }
  1194.  
  1195. What you really want is:
  1196.  
  1197.         for (;;) {
  1198.           cout << "Name: ";
  1199.           cin >> name;
  1200.           cout << "Age: ";
  1201.           cin >> age;
  1202.           cin.ignore(INT_MAX, '\n');
  1203.         }
  1204.  
  1205. ==============================================================================
  1206.  
  1207. Q32: How can I "reopen" cin and cout in binary mode under DOS and/or OS/2?
  1208.  
  1209. Here's the typical scenario that leads to this question: Someone wants to do
  1210. binary I/O using cin and cout, but their operating system (such as DOS or
  1211. OS/2) insists on doing translations on carriagereturn-linefeed pairs.
  1212.  
  1213. Here's the answer: The predefined streams cin, cout, cerr are assumed to be
  1214. text streams, and there is no standard way to cause them to be opened in
  1215. binary mode.  Closing the streams and attempting to reopen them in binary mode
  1216. might have unexpected or undesirable results.
  1217.  
  1218. On systems where it makes a difference, the implementation might provide a way
  1219. to make them binary streams, but you would have to check the manuals to find
  1220. out.
  1221.  
  1222. --
  1223. Paradigm Shift, Inc. / P.O. Box 5108 / Potsdam, NY  13676
  1224. Technology consulting services
  1225. cline@parashift.com / Voice: 315-353-6100 / FAX: 315-353-6110
  1226.  
  1227.  
  1228.